using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ScannerLib.FrameGrabber;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using ScannerLib.Visualizer;

namespace TestCalib
{
    public partial class TestFrameGrabber : Form
    {
        private Capture m_capture;
        private IntPtr m_lastBitmap = IntPtr.Zero;

        public TestFrameGrabber()
        {
            InitializeComponent();

            m_capture = new Capture(0, 30,640,480);
            m_capture.FrameReady += new EventHandler(FrameReady);
        }

        private void UpdateFrame(object sender, EventArgs e)
        {
            if (!m_capture.Started)
                return;

            Bitmap prev = null;
            IntPtr newHandle = IntPtr.Zero;
            try
            {
                newHandle = m_capture.GetBitMap();
            }
            catch (Exception ex)
            {
                return;
            }

            if (m_lastBitmap != IntPtr.Zero)
            {
                prev = m_portal.Image as Bitmap;
                Marshal.FreeCoTaskMem(m_lastBitmap);
            }

            m_lastBitmap = newHandle;
            
            Bitmap image= new Bitmap(m_capture.Width, m_capture.Height, m_capture.Stride , PixelFormat.Format24bppRgb, m_lastBitmap );
            //image.RotateFlip(RotateFlipType.RotateNoneFlipY);
            m_portal.Image = image;

            if (prev != null)
                prev.Dispose();
        }

        private void FrameReady(object sender, EventArgs e)
        {
            if (!m_capture.Started)
                return;

            if (InvokeRequired)
            {
                BeginInvoke(new EventHandler(UpdateFrame), this, e);
            }
            else
            {
                UpdateFrame(this, e);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (m_capture.Started)
            {
                m_capture.Pause();
                button1.Text = "Start";
            }
            else
            {
                m_capture.Start();
                button1.Text = "Pause";
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            bool started = m_capture.Started;

            m_capture.Pause();
            Application.DoEvents();

            if (m_lastBitmap != IntPtr.Zero)
            {
                HoughSnapshot hs = new HoughSnapshot();
                hs.BoundBitmap = (Bitmap)m_portal.Image;
                hs.BoundCapture = m_capture;
                hs.BoundIntPtr = m_lastBitmap;

                hs.ShowDialog(this);

            }

            if (started)
                m_capture.Start();
        }

        
    }
}